package com.example.administrator.yanfoxconn.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.CarListAdapter;
import com.example.administrator.yanfoxconn.adapter.DNReformAdapter;
import com.example.administrator.yanfoxconn.adapter.KMDMTBoxAdapter;
import com.example.administrator.yanfoxconn.bean.KMDMT;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.DateTimePickDialog30Util;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.MyListView;
import com.example.administrator.yanfoxconn.widget.SwipeListViewOne;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import androidx.annotation.RequiresApi;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @Description 多媒体设备 自己的列表
 * @Author song
 * @Date 8/2/21 5:16 PM
 */
public class KMDmtListActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTittle;//標題

    @BindView(R.id.lv_list)
    SwipeListViewOne myListView;

    private String url;
    private String result;
    private String from,flag;

private Boolean isFirst=true;
    private String initStartDateTime; // 初始化开始时间
    private Date selectTime = null;//所選時間
    private Date curDate = null;//當前時間
    private String curDates;//當前時間
    private String minDate ;//最小時間
    private SimpleDateFormat formatter;
    private KMDmtListActivity mContext = this;

    private List<KMDMT> list;
    private CarListAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_km_dmt_list);
        ButterKnife.bind(this);
        btnBack.setOnClickListener(this);
from=getIntent().getStringExtra("from");
flag=getIntent().getStringExtra("flag");
if (from.equals("out")){
    tvTittle.setText("已取用");
}else{

    tvTittle.setText("已預約");
}
        list = new ArrayList<KMDMT>();
        getList();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_title_left:
                    finish();
                break;
        }
    }

    /**
     * 獲取所有設備
     */
    private void getList() {
        showDialog();

        String name = null;
        try {
            name = URLEncoder.encode(URLEncoder.encode(FoxContext.getInstance().getName(), "UTF-8"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        url = Constants.HTTP_DMT_SELF_ALL_LIST + "?creator_id="+name+"&from="+from ;
        new Thread() {
            @Override
            public void run() {
                result = HttpUtils.queryStringForPost(url);

                Log.e("---------", "=getcarLog=fff===" + url);
                Gson gson = new Gson();
                String response = result;

                if (result != null) {
                    Log.e("---------", "result==fff===" + response);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("result").getAsJsonArray();
                        list = new ArrayList<KMDMT>();
                        for (JsonElement type : array) {
                            KMDMT humi = gson.fromJson(type, KMDMT.class);
                            list.add(humi);
                        }
                        Message message = new Message();
                        message.what = Constants.MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    } else {
//                        isShowReturn = false;
                        Message message = new Message();
                        message.what = Constants.MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_TOAST;
                    message.obj = "網絡問題請求失敗,請重試!";
                    mHandler.sendMessage(message);
                }
                dismissDialog();
            }
        }.start();
    }
    private String ids;//获取ID用于上传
    Handler mHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @SuppressLint("HandlerLeak")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.MESSAGE_TOAST://Toast彈出
                    ToastUtils.showLong(KMDmtListActivity.this, msg.obj.toString());
                    myListView.setVisibility(View.VISIBLE);
                    // 适配
                    adapter = new CarListAdapter(KMDmtListActivity.this, list, "dmt",flag);
                    myListView.setAdapter(adapter);
                    setListViewHeightBasedOnChildren(myListView);
                    if (!from.equals("out")){
                        clickCancel();
                    }
                    break;
                case Constants.MESSAGE_UP://t提交提示
                    ToastUtils.showLong(KMDmtListActivity.this, msg.obj.toString());
                    finish();
                    break;
                case Constants.MESSAGE_NOT_NET://t提交提示
                    ToastUtils.showLong(KMDmtListActivity.this, R.string.net_mistake);
                    break;
                case Constants.MESSAGE_DELETE_SUCCESS://t提交提示
                    ToastUtils.showLong(KMDmtListActivity.this,  msg.obj.toString());
                    getList();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    /**
     * 用於解決scrollview嵌套listview導致只顯示一條數據的問題
     * @param listView
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        CarListAdapter listAdapter = (CarListAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() *
                (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }
    private void clickCancel() {//取消預約
        adapter.setOnClickListenerCancel(new CarListAdapter.OnClickListenerCancel() {
            @Override
            public void OnClickListenerC(int position) {
                showDialog();

                String name = null;
                try {
                    name = URLEncoder.encode(URLEncoder.encode(FoxContext.getInstance().getName(), "UTF-8"), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                url = Constants.HTTP_DMT_CANCEL_BOOK + "?creator_id="+name+"&a_id="+list.get(position).getA_id() ;
                new Thread() {
                    @Override
                    public void run() {
                        result = HttpUtils.queryStringForPost(url);

                        Log.e("---------", "=getcarLog=fff===" + url);
                        Gson gson = new Gson();
                        String response = result;

                        if (result != null) {
                            Log.e("---------", "result==fff===" + response);
                            JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                            String errCode = jsonObject.get("errCode").getAsString();
                            if (errCode.equals("200")) {

                                Message message = new Message();
                                message.what = Constants.MESSAGE_DELETE_SUCCESS;
                                message.obj = jsonObject.get("errMessage").getAsString();
                                mHandler.sendMessage(message);
                            } else {
//                        isShowReturn = false;
                                Message message = new Message();
                                message.what = Constants.MESSAGE_DELETE_SUCCESS;
                                message.obj = jsonObject.get("errMessage").getAsString();
                                mHandler.sendMessage(message);

                            }
                        } else {
                            Message message = new Message();
                            message.what = Constants.MESSAGE_DELETE_SUCCESS;
                            message.obj = "網絡問題請求失敗,請重試!";
                            mHandler.sendMessage(message);
                        }
                        dismissDialog();
                    }
                }.start();
            }
        });
    }
}
